import request from '@/utils/request'

export const loginApi = (data) => {
  console.log('正在调用登录API，数据:', data)
  return request({
    url: '/api/auth/login',  // 注意这里改为/auth/login而不是/api/auth/login
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    data: {
      username: data.username,
      password: data.password,
      userType: data.userType
    }
  })
}

export const logoutApi = () => {
  console.log('正在调用登出API')
  return request({
    url: '/auth/logout',
    method: 'POST'
  })
}

export const getUserInfo = () => {
  console.log('正在调用获取用户信息API')
  return request({
    url: '/api/auth/userinfo',
    method: 'GET'
  })
}

export const getStudentByUserId = (userId) => {
  console.log('正在获取学生信息，用户ID:', userId)
  return request({
    url: `/spoc/api/students/by-user/${userId}`,
    method: 'GET'
  })
}

export const getStudentDetailByUserId = (userId) => {
  console.log('正在获取学生详细信息，用户ID:', userId)
  return request({
    url: `/spoc/api/students/detail/by-user/${userId}`,
    method: 'GET',
    transformResponse: [
      function (data) {
        // 处理原始响应数据
        try {
          const parsed = JSON.parse(data)
          // 如果返回的是包装对象，则返回data字段
          // 如果是直接返回的Student对象，则直接返回
          return parsed.data || parsed
        } catch (e) {
          return data
        }
      }
    ]
  })
}

export const getStudentDTOByUserId = (userId) => {
  console.log('正在获取学生DTO信息，用户ID:', userId)
  return request({
    url: `/spoc/api/students/dto/by-user/${userId}`,
    method: 'GET'
  })
}